import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;

public class Demo_UdpEchoServer {
    private DatagramSocket socket = null;
    public Demo_UdpEchoServer(int port) throws SocketException {
        //服务器端需要手动指定端口号
        socket= new DatagramSocket(port);
    }
    public void start() throws IOException {
        //服务器启动
        System.out.println("服务器启动！");
        while(true){
            //1.服务器等待接收数据 解析数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2.服务器计算响应 构建要发送的数据包
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getSocketAddress());
            //3.服务器发送响应
            socket.send(responsePacket);
            //4.打印响应信息
            System.out.printf("[%s:%d]: req=%s, resp=%s\n", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }
    public String process(String request){
        return request;
    }
    public static void main(String[] args) throws IOException {
        Demo_UdpEchoServer server = new Demo_UdpEchoServer(9090);
        server.start();
    }
}